/*
 * Project:     My Project Work, Copyright (C) 2011
 * Created at:  03.08.2011
 */
package de.myprojectwork.presenter;

import de.myprojectwork.common.util.Logger;
import de.myprojectwork.common.util.MyProjectWorkException;
import de.myprojectwork.model.DataManipulationModelImpl;
import de.myprojectwork.model.Table;
import de.myprojectwork.model.dto.Project;
import de.myprojectwork.view.View;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Chris Holdschuh
 */
public abstract class AbstractPresenter<T> implements Presenter {
    
    protected T view;
    
    private static List<AbstractPresenter> allPresenters;
    private static Project currentProject;

    public AbstractPresenter() {
        if (allPresenters == null) 
            allPresenters = new ArrayList<>();
        allPresenters.add(this);
    }

    @Override
    public void setView(View view) {
        this.view = (T) view;
    }

    protected void updateAll() {
        if (allPresenters != null) {
            for(AbstractPresenter presenter : allPresenters) {
                presenter.update();
            }
        }
    }
    
    protected Project getCurrentProject() throws MyProjectWorkException {
        int number = 123;
        if (currentProject == null) {
            List<Project> list = new DataManipulationModelImpl().get(Table.PROJECT, Table.PROJECT.clazz(), null);
            for (Project p : list) {
                if (p.getNumber() == number) {
                    currentProject = p;
                }
            }
        }
        Logger.info("Lade Current-Project Nummer " + number);
        return currentProject;
    }
    
    protected void setCurrentProject(Project project) {
        currentProject = project;
    }
    
    protected <T extends AbstractPresenter> T getPresenter(T clazz) throws MyProjectWorkException {
        T result = null;
        for (AbstractPresenter presenter : allPresenters) {
            if (presenter.getClass().equals(clazz.getClass())) {
                if (result == null) {
                    result = (T) presenter;
                } else {
                    throw new MyProjectWorkException("Es wurde mehr als ein Presenter vom Typ " 
                            + clazz.getClass().getSimpleName() + " gefunden.");
                }
            }
        }
        return result;
    }
    
    /**
     * Aktualisiert die Daten.
     */
    abstract protected void update();
    
}
